<template>
  <div>
    <el-row :gutter="5" style="line-height:50px;">
      <el-col :span="5"
        ><el-cascader
          :props="props"
          placeholder="按标题搜索"
          style="width:100%;"
          v-model="cValue"
          @change="handleChange"
          @expand-change="handleExpandChange"
          :clearable="true"
        ></el-cascader
      ></el-col>
      <el-col :span="8"
        ><el-input
          placeholder="关键字"
          v-model="searchName"
          :disabled="mFlagInputDisabled"
        ></el-input
      ></el-col>
      <el-col :span="2"
        ><el-button
          type="success"
          @click="init()"
          :disabled="mFlagInputDisabled"
          >搜索</el-button
        ></el-col
      >
      <el-col :span="9" style="flex:1;text-align:right;"
        ><el-button type="success" @click="add()" icon="el-icon-plus"
          >添加</el-button
        ></el-col
      >
    </el-row>
    <el-table :data="list" style="width: 100%; ">
      <el-table-column prop="title" label="标题" align="left">
      </el-table-column>
      <el-table-column
        prop="cascaderText"
        label="分类"
        align="center"
        width="150"
      >
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center" width="150">
        <template slot-scope="scope">
          <el-button
            @click="updateStatus(scope.row)"
            v-if="scope.row.status === 1"
            type="success"
            size="small"
            >已上线</el-button
          >
          <el-button
            @click="updateStatus(scope.row)"
            v-else-if="scope.row.status === 2"
            type="danger"
            size="small"
            >已下线</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button
            @click="edit(scope.row)"
            type="text"
            size="small"
            v-if="scope.row.title === '轮播图'"
            >修改</el-button
          >
          <div v-else>
            <el-button @click="edit(scope.row)" type="text" size="small"
              >修改</el-button
            >
            <el-button @click="remove(scope.row)" type="text" size="small"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <my-pagination
      @current-change="handlePageChange"
      ref="myPagination"
      :total="total"
      :pageSize="pageSize"
    ></my-pagination>
  </div>
</template>
<script lang="ts">
import { Vue, Component, Ref } from "vue-property-decorator";
import { MessageBox } from "element-ui";
import {
  reqSearchProducts,
  reqProducts,
  reqCategorys,
  reqProductDelete,
  reqProductUpdateStatus
} from "@/apis/Product";
import { getReqDataNew } from "@/utils/http";
import {
  successDataType,
  failDataType,
  categoryType,
  productCollectionType
} from "CustomTypes";
import { isEqual } from "lodash";
import router from "@/router";
import { rNames } from "@/config/menuConfig";
import { toRoute } from "@/utils";
import MyPagination from "@/components/MyPagination.vue";

@Component({
  name: "Product",
  components: { MyPagination }
})
export default class Product extends Vue {
  @Ref("myPagination")
  private myPagination!: MyPagination;

  private pageNum = 1;
  private pageSize = 20;
  private searchName = "";
  private cValue = [];
  private flagProductDesc = false;
  get mFlagInputDisabled() {
    return this.flagProductDesc;
  }
  private expandChangeList: Array<string> = [];
  get searchType() {
    let result;
    if (this.expandChangeList.length === 2) {
      result = {
        pCategoryId: this.expandChangeList[1]
      };
    } else if (this.expandChangeList.length === 3) {
      result = {
        categoryId: this.expandChangeList[2],
        pCategoryId: this.expandChangeList[1]
      };
    }
    return result;
  }
  private list: Array<productCollectionType> = [];
  private id = 0;
  private props: any = {
    lazy: true,
    async lazyLoad(node: any, resolve: any) {
      const { level, value } = node;

      if (isEqual(0, level)) {
        const temp = [
          {
            value: "name",
            label: "按标题搜索",
            leaf: true
          },
          {
            value: "productDesc",
            label: "按分类搜索",
            leaf: false
          }
        ];

        resolve(temp);
      } else {
        const result = await reqCategorys(
          isEqual(1, level) ? "0" : value,
          false
        );
        const { flag, data } = getReqDataNew(result);

        if (flag) {
          const tempData = (data as successDataType).data;
          const result = tempData.map((item: categoryType) => ({
            value: item._id,
            label: item.name,
            leaf: !isEqual("0", item.parentId)
          }));
          resolve(result);
          return;
        }

        MessageBox.alert((data as failDataType).msg, {
          confirmButtonText: "确定",
          type: "error"
        });
      }
    }
  };

  total = 0;

  add() {
    toRoute(rNames.productAddUpdate);
  }
  edit(data: productCollectionType) {
    // console.log("edit", data);
    const { _id } = data;
    toRoute(rNames.productAddUpdate, { data: _id });
  }
  /**
   * 这是点击最后一个选项才触发
   */
  handleChange(e: any) {
    this.expandChangeList = [...e];
    this.flagProductDesc = isEqual(e[0], "productDesc");
    if (!isEqual(e.length, 1)) this.init();
  }
  /**
   * 响应分页组件中的点击.
   */
  handlePageChange(page: number) {
    this.pageNum = page;
    this.init();
  }
  /**
   * 除了最后一个选项，点击其他选项都触发
   */
  handleExpandChange(e: Array<string>) {
    this.expandChangeList = [...e];
    this.flagProductDesc = isEqual(e[0], "productDesc");
    if (!isEqual(e.length, 1)) this.init();
  }
  async init() {
    let result;

    // 确保每次更新页面，都在当前分页。
    // this.pageNum = isEqual(pageNum, 1) ? pageNum : this.pageNum;

    // 如果能够使用搜索关键字
    if (!this.mFlagInputDisabled) {
      // 当前是“按照标题搜索”，并且关键字非空。
      result =
        this.searchName !== ""
          ? await reqSearchProducts({
              pageNum: this.pageNum,
              pageSize: this.pageSize,
              searchName: this.searchName
            })
          : await reqProducts(this.pageNum, this.pageSize);
    }
    // 如果不能使用搜索关键字，表示当前是“按照分类搜索”
    else {
      result = await reqSearchProducts({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        searchType: this.searchType
      });
    }
    const { flag, data } = getReqDataNew(result);
    console.log("测试登录的错误 flag，不是每次都重现 ", flag);
    console.log("测试登录的错误 data，不是每次都重现 ", data);
    if (flag) {
      const { total, list } = (data as successDataType).data;
      this.total = total;
      this.list = list;

      return;
    }
    MessageBox.alert((data as failDataType).msg, {
      confirmButtonText: "确定",
      type: "error"
    });
  }
  async remove(info: productCollectionType) {
    const result = await reqProductDelete(info._id);
    const { flag, data } = getReqDataNew(result);

    if (flag) {
      //得到数据 (data as successDataType).data;
      await this.init();
      return;
    }

    MessageBox.alert((data as failDataType).msg, {
      confirmButtonText: "确定",
      type: "error"
    });
  }
  async updateStatus(info: productCollectionType) {
    const newStatus = isEqual(info.status, 1) ? 2 : 1;
    const result = await reqProductUpdateStatus(info._id, newStatus);
    const { flag, data } = getReqDataNew(result);

    if (flag) {
      this.list = this.list.map((e: productCollectionType) => {
        e.status = isEqual(e._id, info._id) ? newStatus : e.status;
        return e;
      });
      return;
    }

    MessageBox.alert((data as failDataType).msg, {
      confirmButtonText: "确定",
      type: "error"
    });
  }
  mounted() {
    this.init();
  }
}
</script>
<style>
.el-table__header tr,
.el-table__header th {
  padding: 0;
  height: 50px;
  line-height: 50px;
  text-align: left;
}
</style>
